<template>
  <div class="space-y-6">
    <!-- 角色名称 -->
    <div>
      <label class="block text-sm font-medium text-gray-700 mb-2">角色名称 *</label>
      <input
        v-model="localForm.name"
        type="text"
        placeholder="请输入角色名称"
        class="w-full h-12 px-4 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-[#635BFF] focus:border-transparent"
        @input="updateForm"
      />
    </div>


    <!-- 角色设定 -->
    <div>
      <label class="block text-sm font-medium text-gray-700 mb-2">角色设定 *</label>
      <div class="relative">
        <textarea
          v-model="localForm.prompt"
          placeholder="请详细描述角色的性格特点、背景故事、行为方式等..."
          rows="6"
          maxlength="500"
          class="w-full px-4 py-3 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-[#635BFF] focus:border-transparent resize-none"
          @input="updateForm"
        ></textarea>
        <div class="absolute bottom-2 right-2 text-xs text-gray-400">
          {{ localForm.prompt.length }}/500
        </div>
      </div>
    </div>

    <!-- 角色招呼语 -->
    <div>
      <label class="block text-sm font-medium text-gray-700 mb-2">角色招呼语 *</label>
      <div class="relative">
        <textarea
          v-model="localForm.greeting"
          placeholder="请输入角色的初次问候语..."
          rows="4"
          maxlength="200"
          class="w-full px-4 py-3 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-[#635BFF] focus:border-transparent resize-none"
          @input="updateForm"
        ></textarea>
        <div class="absolute bottom-2 right-2 text-xs text-gray-400">
          {{ localForm.greeting.length }}/200
        </div>
      </div>
      <!-- 操作按钮 -->
      <div class="flex gap-2">
        <button 
          type="button"
          @click="handleAIGreeting"
          class="text-sm text-[#635BFF] hover:text-[#5a4fcf] transition-colors"
        >
          AI生成招呼语
        </button>
      </div>
    </div>
    
    <!-- 角色简介 -->
    <div>
      <label class="block text-sm font-medium text-gray-700 mb-2">角色简介</label>
      <div class="relative">
        <textarea
          v-model="localForm.intro"
          placeholder="一句话或一小段来介绍这个角色的背景与亮点..."
          rows="4"
          maxlength="300"
          class="w-full px-4 py-3 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-[#635BFF] focus:border-transparent resize-none"
          @input="updateForm"
        ></textarea>
        <div class="absolute bottom-2 right-2 text-xs text-gray-400">
          {{ (localForm.intro?.length || 0) }}/300
        </div>
      </div>
      <!-- 操作按钮 -->
      <div class="flex gap-2">
        <button 
          type="button"
          @click="handleAIIntro"
          class="text-sm text-[#635BFF] hover:text-[#5a4fcf] transition-colors"
        >
          AI生成角色简介
        </button>
      </div>
    </div>
    <!-- 外观设定 -->
    <div class="border-t border-gray-200 pt-6">
      <h3 class="text-lg font-semibold text-gray-900 mb-4">外观设定</h3>

      <div class="grid grid-cols-1 lg:grid-cols-2 gap-5">
        <!-- 左侧操作区（上传 / AI 生成） -->
        <div class="lg:col-span-1 space-y-4">
          <div class="space-y-4">
            <!-- 上传方式 -->
            <div class="p-4 rounded-lg ring-1 ring-gray-200 bg-white">
              <div class="text-sm font-medium text-gray-900 mb-2">上传头像</div>
              <input
                ref="fileInputRef"
                type="file"
                accept="image/*"
                class="hidden"
                @change="onFileSelected"
              />
              <button
                type="button"
                @click="handleUpload"
                class="h-10 px-4 rounded-lg bg-gray-100 text-gray-700 hover:bg-gray-200 transition"
              >
                选择图片
              </button>
              <div class="mt-1 text-xs text-gray-400">支持 JPG / PNG</div>
            </div>
            <!-- AI 生成方式 -->
            <div class="p-4 rounded-lg ring-1 ring-gray-200 bg-white">
              <div class="text-sm font-medium text-gray-900 mb-2">AI生成形象</div>
              <button
                type="button"
                @click="handleAIGenerate"
                :disabled="isAvatarLoading"
                class="h-10 px-4 rounded-lg bg-[#635BFF] text-white hover:bg-[#5a4fcf] transition disabled:opacity-50 disabled:cursor-not-allowed"
              >
                {{ isAvatarLoading ? '生成中...' : 'AI生成形象' }}
              </button>
              <div class="mt-1 text-xs text-gray-400">根据“名称 + 设定”生成头像</div>
            </div>
          </div>
        </div>

        <!-- 右侧预览区 -->
        <div class="lg:col-span-1">
          <div class="relative w-full aspect-square rounded-xl ring-1 ring-gray-200 bg-gray-50 overflow-hidden flex items-center justify-center">
            <img v-if="localForm.avatar && !isAvatarLoading" :src="localForm.avatar" alt="avatar" class="w-full h-full object-cover" />
            <div v-else-if="!isAvatarLoading" class="text-gray-400 text-sm">尚未选择形象</div>
            <!-- loading 覆盖层 -->
            <div v-if="isAvatarLoading" class="absolute inset-0 bg-white/60 flex items-center justify-center">
              <svg class="animate-spin h-8 w-8 text-[#635BFF]" viewBox="0 0 24 24">
                <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8v4a4 4 0 00-4 4H4z"></path>
              </svg>
            </div>
          </div>
        </div>

        <!-- AI生成角色按钮 -->
        <!-- <div class="mt-4">
          <button 
            type="button"
            @click="handleGenerateRole"
            :disabled="!canGenerate"
            class="w-full h-10 px-4 rounded-lg bg-[#635BFF] text-white hover:bg-[#5a4fcf] disabled:opacity-50 disabled:cursor-not-allowed transition-colors flex items-center justify-center gap-2"
          >
            <svg v-if="isGenerating" class="w-4 h-4 animate-spin" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"></path>
            </svg>
            <svg v-else class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z"></path>
            </svg>
            {{ isGenerating ? 'AI生成中...' : 'AI帮助设计角色' }}
          </button>
        </div> -->
      </div>
    </div>

    <!-- 语音配置 -->
    <VoiceSettings
      v-model="localForm.voice"
      @update:modelValue="updateForm"
      @preview="handleVoicePreview"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, watch, computed } from 'vue'
import VoiceSettings from './VoiceSettings.vue'
import { characterInfo } from '@/api'
import { VoiceSSEPlayer } from '@/utils/voiceSSEPlayer'

interface CharacterForm {
  name: string
  prompt: string
  greeting: string
  intro?: string
  voice: string
  avatar?: string
}

const props = defineProps<{
  form: CharacterForm
}>()

const emit = defineEmits<{
  'update:form': [form: CharacterForm]
}>()

const localForm = ref({ ...props.form })
const isGenerating = ref(false)
const isAvatarLoading = ref(false)
const fileInputRef = ref<HTMLInputElement | null>(null)

// 监听props变化
watch(() => props.form, (newForm) => {
  localForm.value = { ...newForm }
}, { deep: true })

// 更新表单
const updateForm = () => {
  emit('update:form', { ...localForm.value })
}

// 检查是否可以生成角色
const canGenerate = computed(() => {
  return localForm.value.name.trim() !== '' && 
         localForm.value.prompt.trim() !== '' && 
         !isGenerating.value
})

// 处理头像上传
const handleUpload = () => {
  fileInputRef.value?.click()
}

const onFileSelected = async (e: Event) => {
  const input = e.target as HTMLInputElement
  const file = input.files && input.files[0]
  if (!file) return
  // 简单校验类型与大小（可按需调整）
  if (!file.type.startsWith('image/')) {
    alert('请选择图片文件')
    input.value = ''
    return
  }
  isAvatarLoading.value = true
  try {
    const res = await characterInfo.uploadAvatar(file)
    if (res.code === 0 && res.data) {
      localForm.value.avatar = res.data as unknown as string
      updateForm()
    } else {
      alert(res.msg ?? (res as any).message ?? '上传失败，请稍后重试')
    }
  } catch (err) {
    console.error('上传失败', err)
    alert('上传失败，请稍后重试')
  } finally {
    isAvatarLoading.value = false
    input.value = ''
  }
}

// 处理AI生成头像（形象）
const handleAIGenerate = async () => {
  if (!localForm.value.name.trim() || !localForm.value.prompt.trim()) {
    alert('请先填写角色名称和角色设定')
    return
  }
  try {
    isAvatarLoading.value = true
    const res = await characterInfo.assistAvatar({
      name: localForm.value.name,
      prompt: localForm.value.prompt
    })
    // 期望返回 { code:0, data:[url1, url2], message:'ok' }
    let first: string | undefined
    if (Array.isArray(res?.data) && res.data.length > 0) {
      first = res.data[0]
    } else if (typeof res === 'string') {
      first = res
    }
    if (first) {
      localForm.value.avatar = first
      updateForm()
    } else {
      alert('AI生成形象失败，请稍后重试')
    }
  } catch (e) {
    console.error('AI生成形象失败:', e)
    alert('AI生成形象失败，请稍后重试')
  }
  finally {
    isAvatarLoading.value = false
  }
}

// 处理系统模板
const handleSystemTemplate = () => {
  console.log('选择系统模板')
  // TODO: 实现系统模板选择功能
}

// 语音播放器实例
let voicePlayer: VoiceSSEPlayer | null = null

// 处理语音试听 - 使用封装的 SSE 播放器
const handleVoicePreview = async () => {
  console.log('试听语音:', localForm.value.voice)
  if (!localForm.value.voice) {
    alert('请先选择角色音色')
    return
  }
  
  try {
    // 如果已有播放器在播放，先停止
    if (voicePlayer) {
      voicePlayer.stop()
      voicePlayer = null
    }

    const reqUrl = `/api/voice/play?voiceId=${encodeURIComponent(localForm.value.voice)}`
    console.log('语音试听请求URL:', reqUrl)
    console.log('语音ID:', localForm.value.voice)

    // 使用封装的语音 SSE 播放器
    voicePlayer = new VoiceSSEPlayer({
      sampleRate: 22050,
      timeout: 30000, // 增加到30秒
      retryOnError: false, // 不启用错误重试，避免重复播放
      maxRetries: 3, // 最大重试3次
      onStart: () => {
        console.log('开始播放语音试听')
      },
      onEnd: () => {
        console.log('语音试听播放结束')
        voicePlayer = null
      },
      onError: (error) => {
        console.error('语音播放错误:', error)
        // 只有在重试失败后才显示错误提示
        if (!voicePlayer || voicePlayer.getStatus() === 'idle') {
          alert(`语音播放失败: ${error}`)
        }
        voicePlayer = null
      }
    })

    await voicePlayer.play(reqUrl)
    
  } catch (e) {
    console.error('播放失败', e)
    alert('播放失败，请稍后重试')
    voicePlayer = null
  }
}

// AI生成招呼语
const handleAIGreeting = async () => {
  if (!localForm.value.name.trim() || !localForm.value.prompt.trim()) {
    alert('请先填写角色名称和角色设定')
    return
  }
  try {
    const res = await characterInfo.assistGreeting({
      name: localForm.value.name,
      prompt: localForm.value.prompt
    })
    if (res?.code === 0 && (res as any)?.message) {
      localForm.value.greeting = (res as any).message
      updateForm()
    } else if (typeof res === 'string') {
      // 兜底：有些实现可能直接返回字符串
      localForm.value.greeting = res
      updateForm()
    } else {
      alert('生成招呼语失败，请稍后重试')
    }
  } catch (e) {
    console.error('生成招呼语失败:', e)
    alert('生成招呼语失败，请稍后重试')
  }
}

// AI生成角色简介（待对接真实接口）
const handleAIIntro = async () => {
  if (!localForm.value.name.trim() || !localForm.value.prompt.trim()) {
    alert('请先填写角色名称和角色设定')
    return
  }
  try {
    const res: any = await characterInfo.assistIntro({
      name: localForm.value.name,
      prompt: localForm.value.prompt
    })
    // 兼容两种可能：服务端把简介放在 message 或 data
    const intro = (typeof res?.data === 'string' && res?.code === 0)
      ? res.data
      : (typeof res?.message === 'string' && res?.code === 0)
        ? res.message
        : undefined
    if (intro) {
      localForm.value.intro = intro
    } else if (typeof res === 'string') {
      localForm.value.intro = res
    } else {
      alert('生成简介失败，请稍后重试')
    }
    updateForm()
  } catch (e) {
    console.error('AI生成简介失败:', e)
    alert('AI生成简介失败，请稍后重试')
  }
}

// 处理AI生成角色
const handleGenerateRole = async () => {
  if (!canGenerate.value) return
  
  isGenerating.value = true
  
  try {
    console.log('开始AI生成角色...')
    const response = await characterInfo.generateRole({
      name: localForm.value.name,
      prompt: localForm.value.prompt
    })
    
    console.log('AI生成响应:', response)
    
    if (response.code === 0) {
      // 使用AI生成的角色数据更新表单
      const generatedRole = response.data
      localForm.value = {
        name: generatedRole.name,
        prompt: generatedRole.prompt,
        greeting: generatedRole.greeting,
        voice: generatedRole.voice,
        avatar: generatedRole.image
      }
      updateForm()
      alert('AI角色设计完成！')
    } else {
      alert(`生成失败: ${response.msg || '未知错误'}`)
    }
  } catch (error: any) {
    console.error('AI生成失败:', error)
    
    // 更详细的错误处理
    if (error.code === 'ECONNABORTED' || error.message?.includes('timeout')) {
      alert('请求超时，AI生成需要较长时间，请稍后重试')
    } else if (error.response?.status === 500) {
      alert('服务器内部错误，请稍后重试')
    } else if (error.response?.status === 404) {
      alert('接口不存在，请检查服务器配置')
    } else if (error.response?.status >= 400) {
      alert(`请求失败 (${error.response.status}): ${error.response.data?.message || '未知错误'}`)
    } else {
      alert('AI生成失败，请检查网络连接后重试')
    }
  } finally {
    isGenerating.value = false
  }
}
</script>